//registerFile.c

/*
 * Team Name: Focus
 * Team Members: Edward Bassan, Diana Groun
 * File Name: registerFile.c
 * File Description: This File contains the source file
 * for the registeFile. It implements all the methods that
 * will be used by the registerFile in the SC-2. This
 * includes setting and getting register values in the
 * register file.
 */

#include <stdio.h>
#include <stdlib.h>
#include "registerFile.h"
#include "register.h"
#include "global.h"

/*
 * Constructor for RegisterFile
 */
RegFilePtr newRegisterFile() {
	// creating a new registerFile
	RegFilePtr newRegisterFile = (RegFilePtr) malloc(sizeof(RegisterFile));

	// Initializing the 16 registers in the register file
	int i;
	for (i = 0; i < REGISTER_FILE_SIZE; i++) {
		newRegisterFile->registers[i] = newRegister();
	}
	//Stack Pointer
	newRegisterFile->registers[15]->value = 0xFFFF;
	// linking all the methods that will be used by the registerFile
	newRegisterFile->dispalyRegisters = displayRegisterFile;
	newRegisterFile->getRegisterValue = getRegisterValue;
	newRegisterFile->setRegister = RegisterFileSetRegister;

	// returning the new registerFile
	return newRegisterFile;
}

/*
 * Returns the register value of the register specified by the index
 */
unsigned short getRegisterValue(RegFilePtr reg, int index) {

	// error checking
	if (index >= REGISTER_FILE_SIZE) {
		return INDEX_OUT_OF_BOUNDS;
	} else if (reg == NULL ) {
		return NULL_POINTER_ERROR;
	}else if(index < 0){
		return INDEX_OUT_OF_BOUNDS;
	}
	// Getting register
	RegisterPtr r = reg->registers[index];
	// returning value
	return r->value;
}

/*
 * Sets the the register indicated by the index value to the the
 * indicated value
 */
int RegisterFileSetRegister(RegFilePtr reg, int index, unsigned short value) {

	// error checking
	if (index >= REGISTER_FILE_SIZE) {
		return INDEX_OUT_OF_BOUNDS;
	} else if (reg == NULL ) {
		return NULL_POINTER_ERROR;
	}else if(index < 0){
		return INDEX_OUT_OF_BOUNDS;
	}

	// setting the value of the register
	reg->registers[index]->setRegister(reg->registers[index], value);
	return NO_ERROR;
}

/*
 * Prints all the Registers in the Register File to the console
 */
int displayRegisterFile(RegFilePtr reg) {

	// error checking
	if (reg == NULL ) {
		return NULL_POINTER_ERROR;
	}

	// Going through the array of registers and displaying each
	// register's name and value

	int i;
	unsigned short value;
	for (i = 0; i < REGISTER_FILE_SIZE; i++) {
		value = reg->getRegisterValue(reg, i);
		printf("$R%X: %.4X\n", i, value);
	}
return NO_ERROR;
}
/*
 * Main method
 */
/*
int main() {
	RegFilePtr rf = newRegisterFile();
	rf->setRegister(rf, 3, 4);
	printf("%X",rf->getRegisterValue(rf,3));
	return 0;
}
 */
//End of registerFile.h
